'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Plus, Building2, Trash2 } from 'lucide-react';
import { formatMoney, formatDate, getApiUrl } from '@/lib/utils';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { toast } from 'sonner';

type Site = {
  id: string;
  name: string;
  contractAmount: number;
  status: string;
  createdAt: string;
  expenses: { amount: number }[];
  _count: { expenses: number };
};

function SiteList() {
  const [sites, setSites] = useState<Site[]>([]);
  const router = useRouter();

  useEffect(() => {
    fetchSites();
  }, []);

  async function fetchSites() {
    const response = await fetch(getApiUrl('sites'), {
      next: { revalidate: 0 }
    });
    const data = await response.json();
    setSites(data.map((site: Site) => ({
      ...site,
      expenses: site.expenses || []
    })));
  }

  async function deleteSite(id: string) {
    try {
      const response = await fetch(getApiUrl(`sites/${id}`), {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除失败');
      }

      toast.success('工地已删除');
      fetchSites();
      router.refresh();
    } catch (error) {
      toast.error('删除失败');
      console.error('删除工地失败:', error);
    }
  }

  return (
    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
      {sites.map((site) => {
        const totalExpenses = site.expenses.reduce((sum, expense) => sum + expense.amount, 0);
        const remainingBudget = site.contractAmount - totalExpenses;
        const progress = (totalExpenses / site.contractAmount) * 100;

        return (
          <Card key={site.id} className="group relative">
            <Link href={`/sites/${site.id}`}>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">{site.name}</CardTitle>
                <Building2 className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{formatMoney(site.contractAmount)}</div>
                <div className="text-xs text-muted-foreground space-y-1">
                  <div>支出: {formatMoney(totalExpenses)}</div>
                  <div>剩余: {formatMoney(remainingBudget)}</div>
                  <div>状态: {site.status}</div>
                  <div>创建时间: {formatDate(site.createdAt)}</div>
                  <div>支出记录: {site._count.expenses} 条</div>
                  <div className="w-full bg-secondary h-2 rounded-full mt-2">
                    <div
                      className="bg-primary h-2 rounded-full transition-all"
                      style={{ width: `${Math.min(100, progress)}%` }}
                    />
                  </div>
                </div>
              </CardContent>
            </Link>
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>确认删除</AlertDialogTitle>
                  <AlertDialogDescription>
                    确定要删除工地 "{site.name}" 吗？此操作不可恢复。
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>取消</AlertDialogCancel>
                  <AlertDialogAction onClick={() => deleteSite(site.id)}>
                    删除
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </Card>
        );
      })}
    </div>
  );
}

export default function SitesPage() {
  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold tracking-tight">工地管理</h1>
        <Button asChild>
          <Link href="/sites/new">
            <Plus className="mr-2 h-4 w-4" />
            新建工地
          </Link>
        </Button>
      </div>

      <SiteList />
    </main>
  );
} 